package com.baidu.service.impl;
/**
 * Service
 * 体检预约
 */

import com.alibaba.dubbo.config.annotation.Service;
import com.baidu.constant.MessageConstant;
import com.baidu.entity.PageResult;
import com.baidu.entity.QueryPageBean;
import com.baidu.entity.Result;
import com.baidu.mapper.MemberMapper;
import com.baidu.mapper.OrderListDao;
import com.baidu.mapper.OrderSettingMapper;
import com.baidu.pojo.Member;
import com.baidu.pojo.Order;
import com.baidu.pojo.OrderSetting;
import com.baidu.service.OrderListService;
import com.baidu.utils.DateUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderListService.class)
@Transactional
public class OrderListServiceImpl  implements OrderListService {
    @Autowired
    private OrderListDao orderListDao;
    @Autowired
    private OrderSettingMapper orderSettingDao;
    @Autowired
    private MemberMapper memberDao;

    /**
     * 分页查询数据
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Order> page= orderListDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Order> result = page.getResult();
        return new PageResult(total,result);
    }

    /**
     * 添加预约信息
     * @param map
     * @param setmealId
     * @return
     * @throws Exception
     */
    @Override
    public Result add(Map map, Integer[] setmealId) throws Exception {
        //获取预约日期，查看是否有预约设置
        String  orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting=orderSettingDao.findOrderByOrderDate(DateUtils.parseString2Date(orderDate));
        if(orderSetting==null){
            //当天没有预约设置
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //判断是否预约已经满了
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if(reservations >= number){
            //已经约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //查询是否为重复预约
        String  phoneNumber = (String) map.get("phoneNumber");
        Member member= memberDao.findByTelephone(phoneNumber);
        if (member!=null){
            Integer memberId = member.getId();//会员ID
            Order order=new Order();
            for (Integer integer : setmealId) {
                order.setSetmealId(integer);
            }
            order.setMemberId(memberId);
            order.setOrderDate(orderDate);
            //根据条件查询
            List<Order> list= orderListDao.findByCondition(order);
            if (list!=null && list.size()>0){
                //说明用户在重复预约，无法完成再次预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //自动注册
            member=new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(phoneNumber);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            String  birthday = (String) map.get("birthday");
            member.setBirthday(DateUtils.parseString2Date(birthday));
            String age = (String) map.get("age");
            member.setAge(Integer.parseInt(age));
            member.setMarriage((String) map.get("marriage"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }
        //进行预约
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(orderDate);//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        String affirm="0";
        order.setAffirm(affirm);
        order.setAddress((String) map.get("address"));
        for (Integer integer : setmealId) {
            order.setSetmealId(integer);
            orderListDao.add(order);
        }
        orderSetting.setReservations(orderSetting.getReservations()+setmealId.length);
        orderSettingDao.updateOrderReservations(orderSetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS_NOTSURE);
    }

    /**
     * 预约确定
     * @param id
     * @return
     */
    @Override
    public Result orderSure(Integer id) {
        //查询id
        Order order= orderListDao.findById(id);
        String affirm = order.getAffirm();

        if (affirm.equals("0")){
            try {
            String sure="1";
            order.setAffirm(sure);
            //修改确认信息
            orderListDao.changeAffirm(order);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.ORDER_SUCCESS_SUREFAIL);
            }
            return new Result(true,MessageConstant.ORDER_SUCCESS_SURE);
        }else if (affirm.equals("2")){
            try {
                String sure="1";
                order.setAffirm(sure);
                //修改确认信息
                orderListDao.changeAffirm(order);
                //更新设置表
                String orderDate = order.getOrderDate();
                OrderSetting orderSetting = orderSettingDao.findOrderByOrderDate(DateUtils.parseString2Date(orderDate));
                orderSetting.setReservations(orderSetting.getReservations()+1);
                orderSettingDao.updateOrderReservations(orderSetting);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.ORDER_SUCCESS_SUREFAIL);
            }
            return new Result(true,MessageConstant.ORDER_SUCCESS_SURE);
        }
        else {
            return new Result(false,MessageConstant.ORDER_SUCCESS_ALREADY);
        }
    }

    /**
     * 删除预约
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        Order order= orderListDao.findById(id);
        String affirm = order.getAffirm();
        if (!affirm.equals("2")){
           return new Result(false,MessageConstant.DELETE_ORDER_NOTCANCEL);
        }else {
            orderListDao.delete(order);
            return new Result(true,MessageConstant.DELETE_ORDER_SUCCESS);
        }
    }

    /**
     * 取消预约
     * @param id
     * @return
     */
    @Override
    public Result orderCancel(Integer id) {
        //查询id
        Order order= orderListDao.findById(id);
        String affirm = order.getAffirm();
        if (affirm.equals("0")|| affirm.equals("1")){
            try {
                String cancel="2";
                order.setAffirm(cancel);
                //修改确认信息
                orderListDao.changeAffirm(order);
                //更新设置表
                String orderDate = order.getOrderDate();
                OrderSetting orderSetting = orderSettingDao.findOrderByOrderDate(DateUtils.parseString2Date(orderDate));
                orderSetting.setReservations(orderSetting.getReservations()-1);
                orderSettingDao.updateOrderReservations(orderSetting);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.ORDER_SUCCESS_CANCELFAIL);
            }
            return new Result(true,MessageConstant.ORDER_SUCCESS_CANCEL);
        }else {
            return new Result(false,MessageConstant.ORDER_SUCCESS_CANCELALREADY);
        }
    }
}
